const fs = require('fs')
const path = require('path')
var fsPath = path.join(__dirname, '../data')
var readDir = fs.readdirSync(fsPath)
// console.log("readDir-->", readDir)
const port = 3003

let db = {}
readDir.forEach(i => {
  var f = require('../data' + '/' + i)
  j = i.substr(0, i.length - 3)
  db[j] = f
})
db = JSON.stringify(db)
console.log('db-->', db)

// var db1 = db.toJSONString();
// console.log("db1-->", db1);

fs.writeFile('db.json', db, function(err) {
  if (err) {
    return console.error(err)
  }
  console.log('数据写入成功！')
  console.log('--------我是分割线-------------')
  runServer()
})

function runServer() {
  const jsonServer = require('json-server')
  const server = jsonServer.create()
  const middlewares = jsonServer.defaults()
  const router = jsonServer.router('db.json')

  server.use(middlewares)
  server.use(router)
  server.listen(port, () => {
    console.log('JSON Server is running localhost:' + port)
  })
}
